<template>
    <div v-loading="loading">
        <el-row :gutter="20" type="flex" justify="space-around">
            <el-col :sm="24" :md="6">
                <el-select v-model="selectedPlatform" clearable placeholder="请选择平台">
                    <el-option v-for="(item,index) in platforms" :key="item.name" :label="item.displayName"
                        :value="item.name">

                    </el-option>
                </el-select>
            </el-col>
            <el-col :sm="24" :md="8">
                <el-date-picker v-model="selectedDateRange" type="daterange" unlink-panels range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" :shortcuts="shortcuts" format="YYYY 年 MM 月 DD 日">
                </el-date-picker>
            </el-col>
            <el-col :sm="24" :md="6">
                <el-button type="primary" @click="list">
                    查询
                </el-button>
                <el-button @click="import">
                    上传
                </el-button>
            </el-col>
        </el-row>
        <div>
            <el-table :data="datas" style="width: 100%;">
                <el-table-column type="index" label="序号">

                </el-table-column>
                <el-table-column label="数据源">
                    <template #default="scope">
                        {{ niceDataSource(scope.row.dataSourceCode) }}
                    </template>
                </el-table-column>
                <el-table-column label="消费时间">
                    <template #default="scope">
                        {{ niceTime(scope.row.tradingTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="itemName" label="商品">

                </el-table-column>
                <el-table-column label="收支">
                    <template #default="scope">
                        {{ niceAmount(scope.row) }}
                    </template>
                </el-table-column>
            </el-table>

            <el-dialog title="上传账单" v-model="uploading">
                <el-form id="uploadDialog" ref="form" label-width="100px">
                    <el-form-item label="数据来源">
                        <el-select v-model="uploadFromPlatform" width="200px" placeholder="请选择要上传的平台">
                            <el-option v-for="(item,index) in platforms" :key="item.name" :label="item.displayName"
                                :value="item.name">

                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="选择账单文件">
                        <el-upload ref="upload" class="upload-bill" :auto-upload="false" :file-list="fileList"
                            :limit="1" @on-exceed="handleExceed" action="">
                            <template #trigger>
                                <el-button size="small" type="primary">选择账单</el-button>
                            </template>
                            <div style="display: inline-block; padding-left: 15px;" class="el-upload__tip">
                                只能上传csv文件, 大小限制10M
                            </div>
                        </el-upload>
                    </el-form-item>
                    <div style="text-align: right;">
                        <el-button size="small" @click="closeUpload">
                            取消
                        </el-button>
                        <el-button size="small" type="primary" @click="uploadFile">
                            确认上传
                        </el-button>
                    </div>
                </el-form>
            </el-dialog>
        </div>
        <div>
            <el-pagination background layout="prev,pager,next" :total="total" :hide-on-single-page="true"
                :page-size="pageSize" :current-page="pageIndex" @current-change="handlePageChange">

            </el-pagination>
        </div>
    </div>
</template>

<script lang="ts">
    import axios from "axios";
    import apiConfig from '../api/base.ts';

    console.log("REMOTE_API:" +
        apiConfig.baseUrl)

    const directionOut = 0
    const directionIn = 1
    const directionNone = 2

    const api = axios.create({
        baseURL: apiConfig.baseUrl,
    })

    import {
        defineComponent
    } from "vue";

    export default defineComponent({
        name: "ThridPartyPage",
        data() {
            return {
                datas: [],
                dataSources: [],
                startTime: null,
                endTime: null,
                total: 0,
                pageIndex: 1,
                pageSize: 20,
                loading: false,
                uploading: false,
                platforms: [],
                uploadFromPlatform: null,
                uploadingFile: false,
                fileList: [],
                selectedPlatform: "",
                selectedDateRange: '',
                shortcuts: [{
                    text: '最近一周',
                    value: (() => {
                        const end = new Date()
                        const start = new Date()
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                        return [start, end]
                    })(),
                }, {
                    text: '最近一个月',
                    value: (() => {
                        const end = new Date()
                        const start = new Date()
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                        return [start, end]
                    })(),
                }, {
                    text: '最近三个月',
                    value: (() => {
                        const end = new Date()
                        const start = new Date()
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                        return [start, end]
                    })(),
                }],
            }
        },
        methods: {
            list() {
                if (this.loading) {
                    return 0;
                }

                let start = null;
                let end = null;

                if (this.selectedDateRange != '') {
                    start = this.selectedDateRange[0];
                    end = this.selectedDateRange[1];
                }


                let query = {
                    pageIndex: this.pageIndex,
                    pageSize: this.pageSize,
                    platform: this.selectedPlatform,
                    start: start,
                    end: end
                }

                this.loading = true,
                    api.post('/api/ThirdParty/List', query)
                    .then(resp => {
                        if (resp.data.isSuccess) {
                            this.datas = resp.data.result.collection;
                            this.total = resp.data.result.total;
                        } else {
                            this.$message({
                                message: resp.data.message,
                                type: "warning"
                            });
                        }

                        this.loading = false;
                    })
                    .catch(err => {
                        this.$message({
                            message: "加载时发生错误",
                            type: "error"
                        });

                        this.loading = false;
                    })
            },
            niceAmount(sourceData) {
                if (sourceData.incomeOrSpend == directionOut) {
                    return "- " + sourceData.amount
                } else if (sourceData.incomeOrSpend == directionIn) {
                    return "+ " + sourceData.amount
                } else if (sourceData.incomeOrSpend == directionNone) {
                    return "+ " + sourceData.amount
                } else {
                    return "NaN"
                }
            },
            niceDataSource(dataSourceData) {
                let platform = this.platforms.filter(function (value) {
                    return value.name == dataSourceData;
                });

                if (platform != undefined && platform.length > 0) {
                    return platform[0].displayName;
                }

                return dataSourceData
            },
            niceTime(timeStr) {
                return timeStr.replace("T", " ").replace("Z", "").substring(0, 19)
            },
            import() {
                // 导入
                // 选择数据源和文件
                console.log("打开上传账单窗口")
                this.openUpload()
            },
            uploadFile() {
                if (this.$refs.upload.uploadFiles.length == 0) {
                    this.$message({
                        message: "请选择要上传得文件！",
                        type: "warning"
                    });
                }

                // 实际上传
                let file = this.$refs.upload.uploadFiles[0].raw;

                let formData = new FormData();
                formData.append("platform", this.uploadFromPlatform);
                formData.append("file", file);

                // this.uploadingFile = true

                let loadingObj = this.$loading({
                    target: "#uploadDialog"
                });

                api.post("/api/ThirdParty/Import", formData)
                    .then(resp => {
                        if (resp.data.isSuccess) {
                            this.$message({
                                message: resp.data.message,
                                type: "success"
                            })
                            this.closeUpload()
                        } else {
                            this.$message({
                                message: resp.data.message,
                                type: "warning"
                            })
                        }
                        loadingObj.close();
                    }).catch(err => {
                        this.$message({
                            message: "上传时发生错误",
                            type: "error",
                        })
                        loadingObj.close();
                    });
            },
            openUpload() {
                this.uploading = true
            },
            closeUpload() {
                this.uploading = false
                this.initUpload()
            },
            initUpload() {
                this.uploadFromPlatform = null
                this.$refs.upload.uploadFiles.pop();
            },
            handleExceed(files, fileList) {
                console.log("on exceed")
                fileList[0] = files[0]
            },
            handlePageChange(page) {
                console.log("current:" + page);
                this.pageIndex = page;
                this.list();
            },
            loadPlatforms() {
                api.get("/api/BasicSetting/Platform/ListAll")
                    .then(resp => {
                        if (resp.data.isSuccess) {
                            this.platforms = resp.data.result
                        } else {
                            this.$message({
                                message: resp.data.message,
                                type: "warning"
                            })
                        }
                    })
                    .catch(err => {
                        console.log(err);
                        this.$message({
                            message: "加载平台信息异常",
                            type: "error"
                        });

                    });
            }
        },
        mounted() {
            this.loadPlatforms();
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            this.selectedDateRange = [start, end]
            this.list();
        }
    })
</script>

<style>

</style>